#!/usr/bin/env node

/**
 * 构建验证脚本
 * 验证构建产物的完整性和正确性
 */

const fs = require('fs-extra');
const path = require('path');
const chalk = require('chalk');

class BuildValidator {
  constructor() {
    this.buildDir = path.resolve(__dirname, '../build');
    this.requiredFiles = [
      'manifest.json',
      'background.js',
      'popup.html',
      'popup.js',
      'popup.css',
      'options.html',
      'options.js',
      'options.css',
      'hls-downloader.js'
    ];
    this.requiredDirs = [
      'icons',
      'native-host'
    ];
  }

  async validate() {
    console.log(chalk.blue('🔍 开始验证构建产物...'));

    try {
      // 检查构建目录是否存在
      await this.checkBuildDirectory();

      // 检查必需文件
      await this.checkRequiredFiles();

      // 检查必需目录
      await this.checkRequiredDirectories();

      // 验证 manifest.json
      await this.validateManifest();

      // 验证 JavaScript 文件
      await this.validateJavaScriptFiles();

      // 验证图标文件
      await this.validateIcons();

      console.log(chalk.green('✅ 构建验证通过!'));
      return true;

    } catch (error) {
      console.error(chalk.red('❌ 构建验证失败:'), error.message);
      process.exit(1);
    }
  }

  async checkBuildDirectory() {
    if (!(await fs.pathExists(this.buildDir))) {
      throw new Error('构建目录不存在');
    }
    console.log(chalk.gray('  ✓ 构建目录存在'));
  }

  async checkRequiredFiles() {
    console.log(chalk.yellow('📄 检查必需文件...'));

    for (const file of this.requiredFiles) {
      const filePath = path.join(this.buildDir, file);
      if (!(await fs.pathExists(filePath))) {
        throw new Error(`缺少必需文件: ${file}`);
      }

      const stats = await fs.stat(filePath);
      if (stats.size === 0) {
        throw new Error(`文件为空: ${file}`);
      }

      console.log(chalk.gray(`  ✓ ${file} (${this.formatFileSize(stats.size)})`));
    }
  }

  async checkRequiredDirectories() {
    console.log(chalk.yellow('📁 检查必需目录...'));

    for (const dir of this.requiredDirs) {
      const dirPath = path.join(this.buildDir, dir);
      if (!(await fs.pathExists(dirPath))) {
        throw new Error(`缺少必需目录: ${dir}`);
      }

      const files = await fs.readdir(dirPath);
      if (files.length === 0) {
        console.log(chalk.yellow(`  ⚠️  ${dir} 目录为空`));
      } else {
        console.log(chalk.gray(`  ✓ ${dir} (${files.length} 个文件)`));
      }
    }
  }

  async validateManifest() {
    console.log(chalk.yellow('📋 验证 manifest.json...'));

    const manifestPath = path.join(this.buildDir, 'manifest.json');
    const manifest = await fs.readJson(manifestPath);

    // 检查必需字段
    const requiredFields = ['manifest_version', 'name', 'version', 'description'];
    for (const field of requiredFields) {
      if (!manifest[field]) {
        throw new Error(`manifest.json 缺少必需字段: ${field}`);
      }
    }

    // 检查 manifest 版本
    if (manifest.manifest_version !== 3) {
      throw new Error('manifest_version 必须为 3');
    }

    // 检查权限
    if (!manifest.permissions || !Array.isArray(manifest.permissions)) {
      throw new Error('manifest.json 缺少 permissions 字段');
    }

    // 检查背景脚本
    if (!manifest.background || !manifest.background.service_worker) {
      throw new Error('manifest.json 缺少 background.service_worker 配置');
    }

    console.log(chalk.gray(`  ✓ manifest.json 验证通过 (v${manifest.version})`));
  }

  async validateJavaScriptFiles() {
    console.log(chalk.yellow('⚙️  验证 JavaScript 文件...'));

    const jsFiles = this.requiredFiles.filter(f => f.endsWith('.js'));

    for (const jsFile of jsFiles) {
      const filePath = path.join(this.buildDir, jsFile);
      const content = await fs.readFile(filePath, 'utf8');

      // 基本语法检查
      try {
        // 简单的语法检查 - 检查是否有明显的语法错误
        if (content.includes('console.log') && process.env.NODE_ENV === 'production') {
          console.log(chalk.yellow(`  ⚠️  ${jsFile} 包含 console.log (生产环境应移除)`));
        }

        // 检查是否有基本的 JavaScript 结构
        if (!content.trim()) {
          throw new Error(`${jsFile} 文件为空`);
        }

        console.log(chalk.gray(`  ✓ ${jsFile}`));
      } catch (error) {
        throw new Error(`${jsFile} 语法错误: ${error.message}`);
      }
    }
  }

  async validateIcons() {
    console.log(chalk.yellow('🎨 验证图标文件...'));

    const iconsDir = path.join(this.buildDir, 'icons');
    const requiredIcons = ['icon16.png', 'icon32.png', 'icon48.png', 'icon128.png'];

    for (const icon of requiredIcons) {
      const iconPath = path.join(iconsDir, icon);
      if (!(await fs.pathExists(iconPath))) {
        throw new Error(`缺少图标文件: icons/${icon}`);
      }

      const stats = await fs.stat(iconPath);
      if (stats.size === 0) {
        throw new Error(`图标文件为空: icons/${icon}`);
      }

      console.log(chalk.gray(`  ✓ icons/${icon} (${this.formatFileSize(stats.size)})`));
    }
  }

  formatFileSize(bytes) {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
  }
}

// 运行验证
if (require.main === module) {
  const validator = new BuildValidator();
  validator.validate().catch(console.error);
}

module.exports = BuildValidator;
